import { useCallback, useEffect, useState, useRef } from "react";

export function useMove(ref: React.RefObject<HTMLDivElement>) {
  const [isMoving, setIsMoving] = useState(false);
  const offsetRef = useRef({ x: 0, y: 0 }); // 使用 ref 存储 offset，避免不必要的重新渲染

  const handleMouseDown = useCallback(
    (e: MouseEvent) => {
      if (ref.current) {
        document.body.style.cursor = "grabbing";
        document.body.style.userSelect = "none";
        const { left, top } = ref.current.getBoundingClientRect();
        setIsMoving(true);
        offsetRef.current = {
          x: e.clientX - left,
          y: e.clientY - top,
        };
      }
    },
    [ref]
  );

  const handleMouseMove = useCallback(
    (e: MouseEvent) => {
      e.stopPropagation(); // 阻止事件冒泡，避免影响其他元素的拖拽
      if (isMoving && ref.current) {
        const left = e.clientX - offsetRef.current.x;
        const top = e.clientY - offsetRef.current.y;

        ref.current.style.left = "0px";
        ref.current.style.top = "0px";
        ref.current.style.transform = `translate(${left}px, ${top}px)`;
      }
    },
    [isMoving, ref]
  );

  const handleMouseUp = useCallback(() => {
    document.body.style.cursor = "auto";
    document.body.style.userSelect = "auto";
    setIsMoving(false);
  }, []);

  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    console.log("拖拽启动了");
    element.addEventListener("mousedown", handleMouseDown);
    document.addEventListener("mousemove", handleMouseMove);
    document.addEventListener("mouseup", handleMouseUp);

    return () => {
      element.removeEventListener("mousedown", handleMouseDown);
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", handleMouseUp);
    };
  }, [handleMouseDown, handleMouseMove, handleMouseUp, ref.current]);

  return { isMoving };
}
